package com.ts.proj.json;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.export.styler.ExcelExportStylerBorderImpl;
import com.ts.base.controller.BaseController;
import com.ts.common.constant.*;
import com.ts.proj.entity.*;
import com.ts.proj.entity.excelEntity.ProjectEntityExcel;
import com.ts.proj.service.*;
import com.ts.util.PageData;
import com.ts.util.StringsUtil;
import com.ts.util.DateUtil;
import com.ts.util.EasyPoiUtil;
import com.ts.util.EntityAttributeUtil;
import com.ts.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import javax.servlet.http.HttpSession;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.util.JsonUtils;
import com.ts.common.constant.ConsoleConstant;
import org.springframework.web.multipart.MultipartFile;

//说明 字符串：Project，作为替换字符串 LOWERProject

@RestController
@Slf4j
public class ProjectJson extends BaseController{


    @Value("${upload.location-pre}")
    private String locaionPre ;

    @Value("${upload.split}")
    private String split;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private FileService fileService;

    @Autowired
    private SystemFieldService systemFieldService;

    @Autowired
    private SystemColumnService systemColumnService;

    @Autowired
    private SystemConstantService systemConstantService;

    @Autowired
    private FinanceService financeService;

    @Autowired
    private ProjectMeetingService projectMeetingService;

    @Autowired
    private ErrorprojectService errorprojectService;

    @Autowired
    private SystemUserService systemUserService;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/project-list/{state}/{page}/{size}")
    public Map<String,Object> projectList(@PathVariable("state") Integer state,@PathVariable("page") Integer page, @PathVariable("size") Integer size){
	
 		HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
	
        PageData pageData = this.getPageData();
        //如果state为-2查询所有项目
        if(-2!=state){
            pageData.put("proState", state);
        }

//        if(null!=pageData.get("state")&&!"".equals(pageData.get("state").toString())){
//            pageData.put("proState", pageData.get("state").toString());
//        }

        if(null!=pageData.get("proName")&&!"".equals(pageData.get("proName").toString())){
            pageData.put("proName", pageData.get("proName").toString());
        }
        if(null!=pageData.get("proCategory")&&!"".equals(pageData.get("proCategory").toString())){
            pageData.put("proCategory", pageData.get("proCategory").toString());
        }
        if(null!=pageData.get("proId")&&!"".equals(pageData.get("proId").toString())){
            pageData.put("proId", pageData.get("proId").toString());
        }

        if(null!=pageData.get("proManager")&&!"".equals(pageData.get("proManager").toString())){
            pageData.put("proManager", pageData.get("proManager").toString());
        }

        if(null!=pageData.get("proApprovalTime")&&!"".equals(pageData.get("proApprovalTime").toString())){
            pageData.put("proApprovalTime", pageData.get("proApprovalTime").toString());
        }
        //决策条件
        if(null!=pageData.get("proJueCeInvestType")&&!"".equals(pageData.get("proJueCeInvestType").toString())){
            pageData.put("proJueCeInvestType", pageData.get("proJueCeInvestType").toString());
        }
            //投资对象
        if(null!=pageData.get("proInvestment")&&!"".equals(pageData.get("proInvestment").toString())){
            pageData.put("proInvestment", pageData.get("proInvestment").toString());
        }
            //投资主体
        if(null!=pageData.get("proJueCeInvestCorpus")&&!"".equals(pageData.get("proJueCeInvestCorpus").toString())){
            pageData.put("proJueCeInvestCorpus", pageData.get("proJueCeInvestCorpus").toString());
        }
        //项目尽调方式
        if(null!=pageData.get("proJueCeReport")&&!"".equals(pageData.get("proJueCeReport").toString())){
            pageData.put("proJueCeReport", pageData.get("proJueCeReport").toString());
        }
        //项目真实投资时间（proRealInvestmentTime）
        if(null!=pageData.get("proRealInvestmentTime")&&!"".equals(pageData.get("proRealInvestmentTime").toString())){
            pageData.put("proRealInvestmentTime", pageData.get("proRealInvestmentTime").toString());
        }
        if(null!=pageData.get("proTuichuTime")&&!"".equals(pageData.get("proTuichuTime").toString())){
            pageData.put("proTuichuTime", pageData.get("proTuichuTime").toString());
        }
        //退出方式（proOutWay）
        if(null!=pageData.get("proOutWay")&&!"".equals(pageData.get("proOutWay").toString())){
            pageData.put("proOutWay", pageData.get("proOutWay").toString());
        }
        if(null!=pageData.get("assignmentNumber")&&!"".equals(pageData.get("assignmentNumber").toString())){
            pageData.put("assignmentNumber", pageData.get("assignmentNumber").toString());
        }
        if(null!=pageData.get("averagePrice")&&!"".equals(pageData.get("averagePrice").toString())){
            pageData.put("averagePrice", pageData.get("averagePrice").toString());
        }
        if(null!=pageData.get("totalPrice")&&!"".equals(pageData.get("totalPrice").toString())){
            pageData.put("totalPrice", pageData.get("totalPrice").toString());
        }
        //根据退出开始结束时间段查询
        if(null!=pageData.get("proTuichuBeginTime")&&!"".equals(pageData.get("proTuichuBeginTime").toString())){
            pageData.put("proTuichuBeginTime", pageData.get("proTuichuBeginTime").toString());
        }
        if(null!=pageData.get("proTuichuEndTime")&&!"".equals(pageData.get("proTuichuEndTime").toString())){
            pageData.put("proTuichuEndTime", pageData.get("proTuichuEndTime").toString());
        }

		//用户权限
        if(user.getPowerLevel().equals("0")){
            pageData.put("userId", user.getId());
        }
        pageData.put("belongTo", user.getBelongTo());
        long count = projectService.count(pageData);
        List<ProjectEntity> projects = projectService.findAll(pageData,page-1,size);

        pageData.put("total",count);
        pageData.put("rows", projects);
        return pageData;
    }

    @RequestMapping(value = "/project-detail/{id}")
    public Map<String,Object> projectDetailByProjId(@PathVariable("id") String projId){

        PageData pd = new PageData();
        pd.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        pd.put("uuid", projId);
        List<ProjectEntity> all = projectService.findAll(pd);
        PageData result = new PageData();
        result.put("rows", all);
        return result;

    }
    @RequestMapping(value = "/project-document/{id}")
    public Map<String,Object> projectDocument(@PathVariable("id") String projId){

        PageData pd = new PageData();
        pd.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        pd.put("uuid", projId);
        List<FileEntity> all = fileService.findAll(pd);

        PageData resultList = new PageData();
        resultList.put("rows", all);
        return resultList;
    }

    @RequestMapping(value = "/share-list/{page}/{size}")
    public Map<String ,Object> shareProjectList(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");
        pageData.put("isPublish", "Y");
        long count = projectService.count(pageData);
        List<ProjectEntity> projects = projectService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", projects);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/project-ins-upd-del/{id}")
    public Object logCreateUpdate(@PathVariable("id") String id){ 
	
		ProjectEntity project = projectService.findById(Integer.valueOf(id));
        PageData pageData = this.getPageData();

        List<String> strings = EntityAttributeUtil.entityAttribute(ProjectEntity.class);
		 SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        for(String attr :strings){
            //字段信息维护
            if(null!=pageData.get(attr)&&!"".equals(pageData.get(attr).toString())){
                //目前只能手动添加，这里添加所需要增加和修改的字段
                try {
                    Method[] methods = ProjectEntity.class.getDeclaredMethods();
                    for(int i=0;i<methods.length;i++){
                        Method method = methods[i];
                        Class<?>[] returnType = method.getParameterTypes();
                        if(method.getName().equals("set"+StringsUtil.upperCase(attr))&&!method.getName().contains("get")){
                            if (returnType[0].getName().equals("java.lang.Integer")){
                                method.invoke(project, Integer.valueOf(pageData.getString(attr)));
                            }else if(returnType[0].getName().equals("java.lang.Double")){
                                method.invoke(project, Double.valueOf(pageData.get(attr).toString()));
                            }
                            else{
                                method.invoke(project, pageData.getString(attr));
                            }
                        }
						if(method.getName().equals("setUserId")){
                            project.setUserId(systemUserEntity.getId());
                        }
                        if(method.getName().equals("setBelongTo")){
                            project.setBelongTo(systemUserEntity.getBelongTo());
                        }
						if(method.getName().equals("setPowerLevel")){
                            project.setPowerLevel(systemUserEntity.getPowerLevel());
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }  catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        Integer proState = project.getProState();
        String proLocation = "";
        if(0==proState){
            proLocation = ProjectStateConstant.RUKU;
        }else if(1==proState){
            proLocation = ProjectStateConstant.LIXIANG;
        }else if(2==proState){
            proLocation = ProjectStateConstant.JUECE;
        }else if(3==proState){
            proLocation = ProjectStateConstant.TOUZI;
        }else if(4==proState){
            proLocation = ProjectStateConstant.TOUHOU;
        }else if(5==proState){
            proLocation = ProjectStateConstant.TUICHU;
        }else if(6==proState){
            proLocation = ProjectStateConstant.JIJINTOUHOU;
        }
        if((null == pageData.get("proId") || "".equals(pageData.get("proId").toString())) && "-1".equals(id)){
                project.setProId(KeyUtils.getKey());
        }
        if(null!=pageData.get("city")&&!"".equals(pageData.get("city").toString())){
            String []city = pageData.get("city").toString().split("/");
            String province = "";
            String local = "";
            if(city.length==2){
                 province = city[0];
                 local = city[1];
            }else if(city.length==1){
                province = city[0];
            }
            project.setProProvince(province);
            project.setProCity(local);
        }
        project.setProLocation(proLocation);
        if(null!=pageData.get("deleteFlag")&&!"".equals(pageData.get("deleteFlag").toString())){

            PageData filePageData = new PageData();
            filePageData.put("deleteFlag","N");
            filePageData.put("uuid",project.getUuid());
            List<FileEntity> fileEntityList = fileService.findAll(filePageData);
            for(FileEntity fileEntity : fileEntityList) {
                String path = locaionPre;
                path += fileEntity.getUuid() + split + fileEntity.getState()
                        + split + fileEntity.getState() + "_" + fileEntity.getProjName();
                fileEntity.setDeleteFlag("Y");
                fileService.save(fileEntity);
                File localFile = new File(path);
                localFile.delete();
            }
        }
        if("请选择".equals(pageData.get("proJueCeReport"))) {
            project.setProJueCeReport("");
            project.setProBelieveReason("");
            project.setProThirdOrgName("");
            project.setProReportMoney("");
            project.setProLawOrg("");
            project.setProLawMoney("");
            project.setProFinanceOrg("");
            project.setProFinanceMoney("");
            project.setProAssetsOrg("");
            project.setProAssetsMoney("");
        }else if("采信第三方".equals(pageData.get("proJueCeReport"))){
            project.setProLawOrg("");
            project.setProLawMoney("");
            project.setProFinanceOrg("");
            project.setProFinanceMoney("");
            project.setProAssetsOrg("");
            project.setProAssetsMoney("");
            project.setProImportantNotes("");
        }else if("自己组织尽调".equals(pageData.get("proJueCeReport"))){
            project.setProBelieveReason("");
            project.setProThirdOrgName("");
            project.setProReportMoney("");
        }
        ProjectEntity save = projectService.save(project);
        return save;
    }
    //将excel模板读入程序
    @RequestMapping("/project-downloadExcel/{id}")
    public void downloadExcel(HttpServletResponse response, @PathVariable("id") Integer id) {
        try {

            ProjectEntity project = projectService.findById(id);
            File file = null;
            Map<String, Object> mapData = new HashMap<String, Object>();
            //ruku

                file = ResourceUtils.getFile(locaionPre+"a_excel"+split+"ruku_download.xls");
                SystemUserEntity userEntity = systemUserService.findById(project.getUserId());
                mapData.put("userName",userEntity.getNickname());


            //格式化
            PageData payMethodPd = new PageData();
            payMethodPd.put("deleteFlag","N");
            payMethodPd.put("constantKey","project_payMethod");
            List<SystemConstantEntity> payMethodConstant = systemConstantService.findAll(payMethodPd);
            for(SystemConstantEntity systemConstantEntity: payMethodConstant){
                if (systemConstantEntity.getConstantValue().equals(project.getProPaymentMethod())){
                    mapData.put("payMethod",systemConstantEntity.getConstantValueDesc());
                }else{
                    mapData.put("payMethod","");
                }
            }

//            if(1 == project.getProState()){
//                file = ResourceUtils.getFile(locaionPre+"a_excel"+split+"lixiang_download.xls");
//            }
//
//            if(2 == project.getProState()){
//                file = ResourceUtils.getFile(locaionPre+"a_excel"+split+"juece_download.xls");
//            }
//
//            if(3 == project.getProState()){
//                file = ResourceUtils.getFile(locaionPre+"a_excel"+split+"touzi_download.xls");
//            }
//
//            if(4 == project.getProState()){
//                file = ResourceUtils.getFile(locaionPre+"a_excel"+split+"zhitoutouhou_download.xls");
//            }
//
//            if(5 == project.getProState()){
//                file = ResourceUtils.getFile(locaionPre+"a_excel"+split+"tuichu_download.xls");
//            }
//
//            if(6 == project.getProState()){
//                file = ResourceUtils.getFile(locaionPre+"a_excel"+split+"jijintouhou_download.xls");
//            }
//
//            if(7 == project.getProState()){
//                file = ResourceUtils.getFile(locaionPre+"a_excel"+split+"foujue_download.xls");
//            }
//
//            if(-1 == project.getProState()){
//                file = ResourceUtils.getFile(locaionPre+"a_excel"+split+"yichang_download.xls");
//            }


            mapData.put("project",project);
            TemplateExportParams params = new TemplateExportParams(file.getAbsolutePath(), true);


            Workbook book = ExcelExportUtil.exportExcel(params, mapData);

            //下载方法
            export(response, book, project.getProName()+"-");
//
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * export导出请求头设置
     *
     * @param response
     * @param workbook
     * @param fileName
     * @throws Exception
     */
    private static void export(HttpServletResponse response, Workbook workbook, String fileName) throws Exception {
        response.reset();
        response.setContentType("application/x-msdownload");
        fileName = fileName + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xls");
        ServletOutputStream outStream = null;
        try {
            outStream = response.getOutputStream();
            workbook.write(outStream);
        } finally {
            outStream.close();
        }
    }

    @RequestMapping("/project-download/{stage}")
    public void export(HttpServletResponse response,@PathVariable("stage") Integer stage){
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        param.put("proState", stage);
        List<ProjectEntity> entitys = projectService.findAll(param);
        param.put("isExport", "Y");
        param.put("tableName", StringsUtil.upperCase("projectEntity"));
        List<SystemFieldEntity> all = systemFieldService.findAll(param);
        List<ExcelExportEntity> columnList = new ArrayList<ExcelExportEntity>();
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        //get all columns
        for(SystemFieldEntity systemFieldEntity : all){
            ExcelExportEntity excelExportEntity = new ExcelExportEntity(systemFieldEntity.getFieldCn(), systemFieldEntity.getFieldEn());

            if(EntityUtil.getTypeByFieldName(ProjectEntity.class,systemFieldEntity.getFieldEn()).equals("Integer")){
                excelExportEntity.setType(10);
            }else if(EntityUtil.getTypeByFieldName(ProjectEntity.class,systemFieldEntity.getFieldEn()).equals("String")){
                if(systemFieldEntity.getIsMerge().equals("Y")){
                    excelExportEntity.setMergeVertical(true);
                }
            }
            columnList.add(excelExportEntity);
        }
        //get all data
        for(ProjectEntity te: entitys){
            Map<String, Object> map = new HashMap<>();
            for(SystemFieldEntity systemFieldEntity : all){
                String fieldName = systemFieldEntity.getFieldEn();
                String getFunctionName = "get" + StringsUtil.upperCase(fieldName);
                try {
                    Method method = ProjectEntity.class.getMethod(getFunctionName);
                    Object invoke = method.invoke(te);
                    map.put(fieldName, invoke);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            dataList.add(map);
        }
        PageData temp = new PageData();
        temp.put("deleteFlag", "N");
        temp.put("className", StringsUtil.upperCase("projectEntity"));
        List<SystemColumnEntity> columnEntities = systemColumnService.findAll(temp);
        ExportParams exportParams = null;
        if(1==columnEntities.size()){
            exportParams = new ExportParams(columnEntities.get(0).getExportTitle(), columnEntities.get(0).getExportSheet());
        }else{
            exportParams = new ExportParams("SystemColumnEntity数据表此数据不存在,请确认此条信息", "SHeet");
        }
        exportParams.setStyle(ExcelExportStylerBorderImpl.class);//设置样式,自定义实现IExcelDataHandler<T>
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, columnList, dataList);
        try {
            response.setHeader("Content-Disposition","attachment;filename=" + new String((DateUtil.getID()+".xls").getBytes("UTF-8"), "iso8859-1"));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(response.getOutputStream());
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/project-zip/{id}")
    public void downLoadZip(HttpServletResponse response,@PathVariable("id") Integer id){
        ProjectEntity byId = projectService.findById(id);
//        String basePath = Controller2FTLConstant.WINDOWPATH + Controller2FTLConstant.FILEABSTRACTPATH + byId.getUuid();
        String basePath = locaionPre + byId.getUuid();
        List<File> fileList = new ArrayList<>();
        File file = new File(basePath);
        //返回目录下所有文件和目录绝对路径
        File[] files = file.listFiles();
        if(null != files){
            for(int i=0;i<files.length;i++){
                File temp = files[i];
                if(temp.isFile()){
                    String path = temp.getAbsolutePath() ;
                    fileList.add(new File(path));
                    //递归
                }else if(temp.isDirectory()){
                    File[] tempList = temp.listFiles();
                    if(null==tempList){
                        continue;
                    }
                    for(int j=0;j<tempList.length;j++){
                        File lastFile = tempList[j];
                        if(lastFile.isFile()){
                            String path = lastFile.getAbsolutePath() ;
                            fileList.add(new File(path));
                        }
                    }
                }
            }

        }else{
            File temp = new File(basePath + "/" + "blank.txt");
            if(!temp.exists()){
                try {
                    temp.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            fileList.add(temp);
        }
        try {
            downLoadFiles(fileList, response,byId.getProId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/project-zip")
    public void downLoadZipByAbsolutePath(HttpServletResponse response){
        PageData pd = this.getPageData();
        Integer id = Integer.valueOf(pd.get("id").toString());
        FileEntity byId = fileService.findById(id);
       // String basePath = "/software/upload/" + byId.getUuid() + "/" + byId.getState();
        String basePath = locaionPre + byId.getUuid() + "/" + byId.getState();
        String filePath = basePath + "/" + byId.getFileName();
        File file = new File(filePath);
        if(file.exists()){
            List<File> fileList = new ArrayList<>();
            fileList.add(file);
            try {
                downLoadFiles(fileList, response,byId.getUuid());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
      }

    @RequestMapping("/project-name-check/{name}")
    public String projectNameCheck(@PathVariable("name") String name){
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        param.put("proName", name);
        List<ProjectEntity> all = projectService.findAll(param);
        if(all.size()>0){
            return "exist";
        }else
            return "notexist";
    }


    @RequestMapping(value = "/upload-file/{proId}/{loc}")
    public String uploadFile(HttpServletRequest request, @RequestParam(value="upload")MultipartFile file, @PathVariable("proId") String proId,@PathVariable("loc") String loc) {

        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        PageData pd = new PageData();
        pd.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        pd.put("proId", proId);
        ProjectEntity byId = projectService.findAll(pd).get(0);
        //w文件名称
        String fileName = byId.getId()+"_"+byId.getProName()+"_"+file.getOriginalFilename();
        String fileFolder = locaionPre + byId.getUuid() + split + loc + split;

        File folder = new File(fileFolder);
        if(!folder.exists()){
            folder.mkdirs();
        }
        File dest = new File(fileFolder + fileName);
        try {
            file.transferTo(dest);
            //记入数据库
            FileEntity fileEntity = new FileEntity();

            HttpSession session = this.getRequest().getSession();
            SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
            fileEntity.setUserId(user.getId());
            fileEntity.setBelongTo(user.getBelongTo());
            fileEntity.setFileName(dest.getName());
            fileEntity.setState(loc);
            fileEntity.setProjId(byId.getProId());
            fileEntity.setProjName(byId.getProName());
            fileService.save(fileEntity);
            return byId.getProId();
        } catch (IOException e) {
        }
        return "上传失败！";
    }


    @RequestMapping(value = "/pro-document")
    public Map<String,Object> proDocument(){
        List<PageData> fileList = new ArrayList<>();
        PageData temp = new PageData();
        temp.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<FileEntity> all = fileService.findAll(temp);
        List<PageData> allProjects = fileService.findAllProjects();

        PageData statePd = new PageData();
        statePd.put("constantKey", "proj_state");
        statePd.put("deleteFlag", "N");
        List<SystemConstantEntity> constantEntities = systemConstantService.findAll(statePd);
        List<String> lifeCycleList = new ArrayList<>();
        for(int i=0;i<constantEntities.size();i++) {
            if(!PinyinHelperUtil.getPinYinHeadChar(constantEntities.get(i).getConstantValueDesc()).equals("JJTH")) {
                lifeCycleList.add(PinyinHelperUtil.getPinYinHeadChar(constantEntities.get(i).getConstantValueDesc()));
            }
        }
        //项目名称，文件总数
        for(PageData pd : allProjects){
            PageData fPd = new PageData();
            fPd.put("id", pd.get("uuid").toString());
            fPd.put("proid", pd.get("uuid").toString());
            fPd.put("flag", "pro");
            fPd.put("state", "closed");
            int c = 0;
            //项目生命周期，数量
            for(String str : lifeCycleList){
                UUID uuidId = UUID.randomUUID();
                PageData projPd = new PageData();
                projPd.put("id", uuidId);
                projPd.put("proid", str);
                projPd.put("_parentId", pd.get("uuid").toString());
                projPd.put("state", "closed");
                projPd.put("flag", "lifeCycle");
                projPd.put("upid", pd.get("id"));
                int count = 0;
                //文件名称，数量
                for(FileEntity entity : all){
                    if(entity.getUuid().equals(pd.get("uuid").toString())  && entity.getState().equals(str)){
                            PageData filePd = new PageData();
                            filePd.put("id", UUID.randomUUID());
                            filePd.put("proid", entity.getFileName());
                            filePd.put("_parentId", uuidId);
                            filePd.put("flag", "document");
                            fileList.add(filePd);
                            count++;
                            c++;
                    }
                }
                projPd.put("count", count);

                fileList.add(projPd);
            }
            fPd.put("count", c);
            fileList.add(fPd);
        }
        PageData result = new PageData();
        result.put("rows", fileList);
        return result;
    }

    @RequestMapping(value = "/project-by-proid/{projId}")
    public ProjectEntity projectByProid(@PathVariable("projId") String projId){

        PageData pd = new PageData();
        pd.put("uuid", projId);
        pd.put("deleteFlag","N");
        List<ProjectEntity> all = projectService.findAll(pd);
        if(all.size()==1){
            return all.get(0);
        }
        return new ProjectEntity();

    }


    @RequestMapping("/project-template-download")
    public void export(HttpServletResponse response){
        EasyPoiUtil.exportExcel(new ArrayList<>(),"项目导入模板","template",ProjectEntityExcel.class, "template.xls",response);
    }

    @RequestMapping("/project-check-download/{id}")
    public String  projectCheckDownload(@PathVariable("id") Integer id){
        String result = "error";
        ProjectEntity byId = projectService.findById(id);
//        String basePath = Controller2FTLConstant.WINDOWPATH + Controller2FTLConstant.FILEABSTRACTPATH + byId.getUuid();
//        String basePath = "/software/upload/"+ byId.getUuid();
        String basePath = locaionPre + byId.getUuid();
        List<File> fileList = new ArrayList<>();
        File file = new File(basePath);
        File[] files = file.listFiles();
        if(null!=files&&files.length>0){
            return "download";
        }
        return result;
    }
    @RequestMapping("/project-name-id/{id}")
    public String projectNameId(@PathVariable("id") Integer id){
        ProjectEntity byId = projectService.findById(id);
        return byId.getProName();
    }

    //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    public  HttpServletResponse downLoadFiles(List<File> files, HttpServletResponse response,String proId) throws Exception {

        try {
//            String zipFilenamePath = Controller2FTLConstant.WINDOWPATH + Controller2FTLConstant.FILEABSTRACTPATH + proId ;
            String zipFilenamePath = locaionPre+ proId;
            String zipFileName =  proId + ".zip";
            File fileFolder = new File(zipFilenamePath);
            if(!fileFolder.exists()){
                fileFolder.mkdir();
            }
            File file = new File(zipFilenamePath + "/" + zipFileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            response.reset();
            // response.getWriter()
            // 创建文件输出流
            FileOutputStream fous = new FileOutputStream(file);
            ZipOutputStream zipOut = new ZipOutputStream(fous);
            FileUtil.zipFile(files, zipOut);
            zipOut.close();
            fous.close();
            return new ProjectJson().downloadZip(file, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    public  HttpServletResponse downloadZip(File file, HttpServletResponse response) {
        if (file.exists() == false) {
            System.out.println("待压缩的文件目录：" + file + "不存在.");
        } else {
            try {
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();

                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");

                // 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    File f = new File(file.getPath());
                    f.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return response;
    }

    /**
     *根据项目id查询项目
     * @param id
     * */
    @RequestMapping("/queryPojectById/{id}")
    public ProjectEntity queryPojectById(@PathVariable("id") Integer id){
        return  projectService.findById(id);
    }
}